﻿using System;
using System.Collections.Generic;
using Gp.Input;
using Gp.Scripts.Core;
using QFramework;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Gp.Scripts.GUI {
    public class UnitInfoWindow : DisplayWithUnitUI {
        public GameObject window;
        
        public Image icon;
        
        public TextMeshProUGUI stat;

        
        public TextMeshProUGUI unitName;


        public TMP_Text description;


        public UnitInfoBuffItem buffItemPrefab;
        public Transform buffItemContainer;


        private readonly List<UnitInfoBuffItem> _caches = new ();
        

        private bool _isShowUnitInfoWindowSwitchOn = false;

        
        
        
        
        private void Update() {
            if (Global.Get<InputManager>().CurrentUnitInfoSwitched()) {
                _isShowUnitInfoWindowSwitchOn = !_isShowUnitInfoWindowSwitchOn;
            }

            this.window.SetActive(_isShowUnitInfoWindowSwitchOn);


            var unit = CurrentUnit;
            if (!unit || !this.window.activeInHierarchy) {
                this.stat.text = "";
                return;
            }

            // 更新基本单位信息
            // this.icon.sprite = unit.Avatar;
            this.unitName.text = unit.UnitName;
            this.description.text = unit.Description;
            
            
            // CombatantStat us = unit.RawStat();

            string content = "";
            // foreach (var (key, pair) in us.ValueDic) {
            //     var addition = unit.BonusStatByType(key);
            //     content += key.StatName() + ":  " + pair.Value +
            //                (addition == 0 ? "" : "(+" + addition + ")") + "\n";
            // }
            //
            this.stat.text = content;
            
            
            // 更新状态信息
            // buff 的显示使用 显示对象 -》实体 的结构渲染
            // 当需要显示buff时，优先调用缓存内的buff显示对象进行渲染
            // 当缓存数量不足时，生成新的显示对象
            // 显示对象不会销毁，即当前显示对象的数量为显示过的单位buff的最大数量
            int i = 0;
            foreach (var buff in unit.ComBuff.Buffs) {
                if (_caches.Count <= i) {
                    var obj = Instantiate(buffItemPrefab, buffItemContainer);
                    _caches.Add(obj);
                }
                _caches[i].RenderBuff(buff);
                _caches[i].gameObject.SetActive(true);
                
                i++;
            }

            // 当显示对象超过buff实体数量时，关闭显示对象而不是删除
            for (; i < _caches.Count; i++) {
                _caches[i].gameObject.SetActive(false);
            }

        }
    }
}